package com.shizhanzhe.gxb;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.gxb.base.BaseActivity;
import com.shizhanzhe.gxb.base.UserBean;
import com.shizhanzhe.gxb.brand.BrandFragment;
import com.shizhanzhe.gxb.circle.CircleFragment;
import com.shizhanzhe.gxb.home.HomeFragment;
import com.shizhanzhe.gxb.my.MyFragment;
import com.shizhanzhe.gxb.my.bean.AD;
import com.shizhanzhe.gxb.url.Path;
import com.shizhanzhe.gxb.utils.AdPreference;
import com.shizhanzhe.gxb.utils.BnfStartupAdPageDto;
import com.shizhanzhe.gxb.utils.DownListener;
import com.shizhanzhe.gxb.utils.DownloadUtil;
import com.shizhanzhe.gxb.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.gxb.utils.SharedPreferencesUtils;
import com.shizhanzhe.gxb.vip.VipFragment;
import com.tencent.bugly.beta.Beta;

import java.util.List;
import java.util.Random;

public class MainActivity extends BaseActivity implements View.OnClickListener  {
    private long exitTime = 0;

    private HomeFragment homeFragment;
    private BrandFragment brandFragment;
    private CircleFragment circleFragment;
    private MyFragment myFragment;
    private VipFragment vipFragment;
    private FragmentManager fragmentManager;
    private ImageView homeiv;
    private TextView hometext;
    private ImageView taskiv;
    private TextView tasktext;
    private ImageView teamiv;
    private TextView teamtext;
    private ImageView myiv;
    private TextView mytext;
    private TextView viptext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Beta.init(getApplicationContext(), false);
        ImmersionBar.with(this)
                .statusBarView(R.id.bar_0_view)
                .init();
        initView();
        getData();
        setChioceItem(0);
    }

    @Override
    protected void initView() {
        findViewById(R.id.ll_main_tab_home).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_task).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_team).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_my).setOnClickListener(this);
        findViewById(R.id.ll_main_tab_vip).setOnClickListener(this);
        homeiv = findViewById(R.id.home_iv);
        hometext = findViewById(R.id.home_text);
        taskiv = findViewById(R.id.task_iv);
        tasktext = findViewById(R.id.task_text);
        teamiv = findViewById(R.id.team_iv);
        teamtext = findViewById(R.id.team_text);
        myiv = findViewById(R.id.my_iv);
        mytext = findViewById(R.id.my_text);
        viptext = findViewById(R.id.vip_text);
        fragmentManager = getSupportFragmentManager();
    }

    @Override
    protected void getData() {
        UserBean.uid = (int) SharedPreferencesUtils.getParam(this, "uid", 0);
        UserBean.pid = (int) SharedPreferencesUtils.getParam(this, "pid", 0);
        UserBean.headimg = (String) SharedPreferencesUtils.getParam(this, "headimg", "");
        UserBean.mobile = (String) SharedPreferencesUtils.getParam(this, "mobile", "");
        UserBean.nickname = (String) SharedPreferencesUtils.getParam(this, "nickname", "");
        UserBean.balance = (String) SharedPreferencesUtils.getParam(this, "balance", "");
        UserBean.level = (int) SharedPreferencesUtils.getParam(this, "level", 0);
        UserBean.isuser = (int) SharedPreferencesUtils.getParam(this, "isuser", 0);
        UserBean.divide = Double.parseDouble((String) SharedPreferencesUtils.getParam(this, "income", "0"));
        UserBean.vipdivide = Double.parseDouble((String) SharedPreferencesUtils.getParam(this, "profit", "0"));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
                return;
            }
        }
        getAd();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_main_tab_home:
                setChioceItem(0);
                break;
            case R.id.ll_main_tab_task:
                setChioceItem(1);
                break;
            case R.id.ll_main_tab_team:
                setChioceItem(2);
                break;
            case R.id.ll_main_tab_my:
                setChioceItem(3);
                break;
            case R.id.ll_main_tab_vip:
                setChioceItem(4);
                break;
                default:
        }
    }

    private void getAd(){
        OkHttpDownloadJsonUtil.downloadJson(this, Path.getAd(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                try {
                    Gson gson = new Gson();
                    List<AD.DataBean> list = gson.fromJson(json, AD.class).getData();
                    if (!list.isEmpty()) {
                        AD.DataBean ad = list.get(0);
                        if (list.size() > 1) {
                            ad = list.get(new Random().nextInt(list.size()));
                        }
                        Log.d("____",ad.getGaopic());
                        AdPreference.getInstance().saveStartupAdPage(new BnfStartupAdPageDto(Path.BASE_URL + ad.getGaopic(), ad.getGaourl(), "1536809117"));
                        new DownloadUtil().downloadImg(Environment.getExternalStorageDirectory() + "/MFAd/", Path.BASE_URL + ad.getGaopic(), new DownListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onProgress(int currentLength) {

                            }

                            @Override
                            public void onFinish(String localPath) {

                            }

                            @Override
                            public void onFailure() {
                                AdPreference.getInstance().clear();
                            }
                        });

                    }
                } catch (Exception e) {
                }
            }
        });
    }
    /**
     * 设置点击选项卡的事件处理
     *
     * @param index 选项卡的标号：0, 1, 2, 3
     */
    private void setChioceItem(int index) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        clearChioce(); // 清空, 重置选项, 隐藏所有Fragment
        hideFragments(fragmentTransaction);
        switch (index) {
            case 0:
                hometext.setTextColor(getResources().getColor(R.color.red));
                homeiv.setImageResource(R.mipmap.icon_home2);
                // 如果homeFragment为空，则创建一个并添加
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    fragmentTransaction.add(R.id.frame_layout, homeFragment);
                } else {
                    // 如果不为空，则直接显示
                    fragmentTransaction.show(homeFragment);
                }
                homeFragment.setHomeListener(new HomeFragment.HomeListener() {
                    @Override
                    public void gotovip() {
                        setChioceItem(4);
                    }
                });
                break;
            case 1:
                tasktext.setTextColor(getResources().getColor(R.color.red));
                taskiv.setImageResource(R.mipmap.icon_task2);

                if (brandFragment == null) {
                    brandFragment = new BrandFragment();
                    fragmentTransaction.add(R.id.frame_layout, brandFragment);
                } else {
                    fragmentTransaction.show(brandFragment);
                }
                break;
            case 2:
                teamtext.setTextColor(getResources().getColor(R.color.red));
                teamiv.setImageResource(R.mipmap.icon_team2);
                if (circleFragment == null) {
                    circleFragment = new CircleFragment();
                    fragmentTransaction.add(R.id.frame_layout, circleFragment);
                } else {
                    fragmentTransaction.show(circleFragment);
                }
                break;
            case 3:
                mytext.setTextColor(getResources().getColor(R.color.red));
                myiv.setImageResource(R.mipmap.icon_my2);
                if (myFragment == null) {
                    myFragment = new MyFragment();
                    fragmentTransaction.add(R.id.frame_layout, myFragment);
                } else {
                    fragmentTransaction.show(myFragment);
                }
                myFragment.setListener(new MyFragment.MyListener() {
                    @Override
                    public void inviteclick(int homeinto) {
                        setChioceItem(4);
                    }
                });
                break;
            case 4:
                viptext.setTextColor(getResources().getColor(R.color.red));
                if (vipFragment == null) {
                    vipFragment = new VipFragment();
                    fragmentTransaction.add(R.id.frame_layout, vipFragment);
                } else {
                    fragmentTransaction.show(vipFragment);
                }
                break;
                default:
        }
        fragmentTransaction.commit();
    }

    /**
     * 当选中其中一个选项卡时，其他选项卡重置为默认
     */
    private void clearChioce() {
        hometext.setTextColor(getResources().getColor(R.color.color_huise));
        tasktext.setTextColor(getResources().getColor(R.color.color_huise));
        teamtext.setTextColor(getResources().getColor(R.color.color_huise));
        mytext.setTextColor(getResources().getColor(R.color.color_huise));
        viptext.setTextColor(getResources().getColor(R.color.color_huise));
        homeiv.setImageResource(R.mipmap.icon_home1);
        taskiv.setImageResource(R.mipmap.icon_task1);
        teamiv.setImageResource(R.mipmap.icon_team1);
        myiv.setImageResource(R.mipmap.icon_my1);

    }

    /**
     * 隐藏Fragment
     *
     * @param fragmentTransaction
     */
    private void hideFragments(FragmentTransaction fragmentTransaction) {
        if (homeFragment != null) {
            fragmentTransaction.hide(homeFragment);
        }
        if (brandFragment != null) {
            fragmentTransaction.hide(brandFragment);
        }
        if (circleFragment != null) {
            fragmentTransaction.hide(circleFragment);
        }
        if (myFragment != null) {
            fragmentTransaction.hide(myFragment);
        }
        if (vipFragment != null) {
            fragmentTransaction.hide(vipFragment);
        }
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
